<?php

class payment_manager extends a_base_model {

    public function __construct() {
        parent::__construct();
    }

    public function load_enabled_drivers($site_id, $currency) {
        $drivers = NULL;
        $query = $this->db()
                        ->where("site_id", $site_id)
                        ->where_in('currency', array("$currency", "*"))
                        ->where("enabled", "1")
                        ->order_by("sequence", "ASC")
                        ->get("payment_drivers");
        if ($query->num_rows() > 0) {
            $drivers = array();
            foreach ($query->result() as $driver) {
                $class_name = "payment_driver_" . $driver->driver_id;
                $drivers[$driver->driver_id] = new $class_name($driver);
            }
        }

        return $drivers;
    }

    public function get_payment_driver($driver_id, $site_id=NULL) {
        if ($site_id !== NULL) $this->db()->where("site_id", $site_id);
        $query = $this->db()->where("driver_id", $driver_id)->get("payment_drivers");
        if ($query->num_rows() > 0) {
            $result = $query->result();
            $row = $result[0];
            $class_name = "payment_driver_" . $row->driver_id;
            return new $class_name($row);
        } else {
            return NULL;
        }
    }

    public function save_payment_info($order_id_or_object, $driver_id, $driver_note='', $user_note='') {
        $order = get_object($order_id_or_object, "order_m_order");
        $this->db()->where('order_id', $order->id)
                ->delete('order_payment_info');
        $this->db()->set('payment_driver_id', $driver_id)
                ->set('user_note', $user_note)
                ->set('driver_note', $driver_note)
                ->set('order_id', $order->id)
                ->insert('order_payment_info');
    }

    /**
     * Get base payment information for an order.For example
     * for an order paid by master card the base info would
     * only say the driver id and what kind of card is used.
     * But to know the card number (which is not a good security practice)
     * or online processing transaction id etc you must
     * call the payment_driver's transactional information method.
     *
     * @param int|order_m_order $order_id_or_object
     * @return payment_info_m_order
     */
    public function get_payment_info($order_id_or_object) {
        $order = get_object($order_id_or_object, "order_m_order");
        if ($order !== NULL) {
            $info = new payment_info_m_order();
            $info->get_by_order_id($order->id);
            if ($info->exists()) {
                return $info;
            } else {
                return NULL;
            }
        } else {
            return NULL;
        }
    }

}

?>
